package org.tinygame.herostory;

import com.google.protobuf.GeneratedMessageV3;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author shkstart
 * @create 2022-05-04 19:00
 */
public class GameMsgEncoder extends ChannelOutboundHandlerAdapter {
    //日志
    static private final Logger LOGGER= LoggerFactory.getLogger(GameMsgEncoder.class);
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(null==msg||!(msg instanceof GeneratedMessageV3)){
            super.write(ctx,msg,promise);
            return;
        }


        //服务端处理完了请求，根据消息类型生成消息编号，编码准备下发给客户端
        int msgCode=GameMsgRecognizer.getMsgCodeByMsgClazz(msg.getClass());
        if(msgCode<=-1){
            LOGGER.error("无法识别的消息, msgClazz= {}",msg.getClass().getName());
            return;
        }

        //将消息转换成字节数组，准备发送
        byte[] msgBody = ((GeneratedMessageV3) msg).toByteArray();

        ByteBuf byteBuf=ctx.alloc().buffer();
        //构建消息头
        byteBuf.writeShort((short)0);
        byteBuf.writeShort((short)msgCode);
        //构建消息体
        byteBuf.writeBytes(msgBody);

        BinaryWebSocketFrame frame=new BinaryWebSocketFrame(byteBuf);
        super.write(ctx,frame,promise);
    }
}
